<?php
/**
 * Created by PhpStorm.
 * User: ZT
 * Date: 2020/6/1 0001
 * Time: 17:14
 **/
namespace common\models\info;

use common\component\BaseActiveRecord;
use common\component\Constant;
use common\utils\CommonUtil;
use yii\behaviors\TimestampBehavior;
use yii\helpers\Url;

/**
 *
 * @property int $id  自增主键id
 * @property int $article_id 文章id
 * @property int $category_id  分类id
 * @property int $created_at 创建时间
 */
class CategoryRelation extends BaseActiveRecord
{

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%zt_category_relation}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['article_id', 'category_id', 'created_at'], 'integer'],
            [['article_id', 'category_id'], 'unique', 'targetAttribute' => ['article_id', 'cate_id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'article_id' => '文章 ID',
            'category_id' => '分类 ID',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at']
                ]
            ]
        ];
    }

    /**
     * 批量写入数据库
     * @param $data_arr
     * @return bool
     */
    public static function ArticleCateBatchInsert($data_arr)
    {
        try {
            $result = \Yii::$app->db->createCommand()->batchInsert(self::tableName(), ["article_id", "category_id", "created_at"], array_map(function ($data) {
                return ['article_id' => $data['article_id'], 'category_id' => $data['category_id'], "created_at" => time()];
            }, $data_arr))->execute();
        } catch (Exception $e) {
            \Yii::error("批量导入数据错误，原因:" . $e->getMessage() . "\n 数据：\n" . var_export($data_arr, true));
            return false;
        }
        return $result;
    }

    public static function isInsert($article_id, $cate_id)
    {
        return static::find()->where(['article_id' => $article_id, 'category_id' => $cate_id])->count();
    }

    public static function insertInto($article_id, $cate_arr)
    {
        $cate_id_arr = self::getArticleCateData($article_id);
        $cate_id_insert = array_diff($cate_arr, $cate_id_arr);
        $cate_id_delete = array_diff($cate_id_arr, $cate_arr);
        $data_arr_insert = [];
        $i = 0;
        if ($cate_id_insert) {
            foreach ($cate_id_insert as $cate_id) {
                $data_arr_insert[$i]['article_id'] = $article_id;
                $data_arr_insert[$i]['category_id'] = (int)$cate_id;
                $i++;
            }
            self::ArticleCateBatchInsert($data_arr_insert);
        }

        if ($cate_id_delete) {
            foreach ($cate_id_delete as $cate_id) {
                static::deleteAll(['article_id' => $article_id, 'category_id' => $cate_id]);
            }
        }
    }

    /**
     * 获取文章分类（默认不取缓存数据）
     * @param $article_id
     * @param $flag
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getArticleCateData($article_id, $flag = false)
    {
        $key = "article:cate:data:id:" . $article_id;
        if (!$flag) {
            $data = static::find()->where(['article_id' => $article_id])->asArray()->all();
            $data = $data ? array_values(array_column($data, 'category_id')) : [];
        }
        return $data;
    }

    public static function getArticleCate($cate_id)
    {
        $where = ['and'];
        $where[] = ['in', 'category_id', $cate_id];
        $data = static::find()->where($where)->asArray()->orderBy('id desc')->all();
        return $data ? array_values(array_column($data, 'article_id')) : [];
    }

    public static function getCateNameByArticle($article_id)
    {
        $data = static::find()->alias('a')
            ->select('cate_name')
            ->leftJoin('info_category as b', 'b.id = a.category_id')
            ->where(['a.article_id' => $article_id])
            ->asArray()
            ->all();
        return $data ?: [];
    }

    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }


}
